from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView,RetrieveAPIView
# Create your views here.
from rest_framework.response import Response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area, Address
from areas.serializers import AreasSerializer,AddressSerializer
from users.models import User


class AreasView(ListAPIView):
    """
    获取省的信息
    """
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent=None)

class AreaView(CacheResponseMixin, ListAPIView):
    """
    获取区县的信息
    """
    serializer_class = AreasSerializer

    def get_queryset(self):
        pk = self.kwargs["pk"]
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView,ListAPIView,UpdateAPIView,DestroyAPIView):
    """
    保存收货地址,增删改查以及显示
    """
    serializer_class = AddressSerializer
    # request.user不可以直接获取，所以不能这么写，需要重写
    # queryset = Address.objects.filter(users =request.users )
    def get_queryset(self):
        return  Address.objects.filter(user = self.request.user,is_deleted = False)

    # .then(response= > {
    #     this.addresses = response.data.addresses;,获取到的addresses 为undefined
    # 数据全部在request.data中，所以需要重写返回的格式
    def list(self, request, *args, **kwargs):
        """
        展示所有收货地址
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)
        return Response({"addresses":serializer.data})

    def destroy(self, request, *args, **kwargs):
        """
        因为为物理删除，所以改为逻辑删除
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


class AddressDefaultView(UpdateAPIView):
    def get_queryset(self):
        return  Address.objects.filter(user = self.request.user)


    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        request.user.defult_address = instance
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)



